package monitor;

import observer.EnvironmentObserver;
//import sun.management.Sensor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import observer.EnvironmentObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 环境监测器
 * 作为被观察者，管理传感器并通知观察者
 */
public class EnvironmentMonitor {
    List<EnvironmentObserver> observers = new ArrayList<>();
    Map<String, Sensor> sensors = new HashMap<>();
    Map<String, Map<String, Double>> sensorData = new HashMap<>();

    public void registerSensor(Sensor sensor) {
        sensors.put(sensor.getName(), sensor);
        sensorData.put(sensor.getName(), new HashMap<>());
    }

    public void unregisterSensor(String sensorId) {
        sensors.remove(sensorId);
        sensorData.remove(sensorId);
    }

    public void registerObserver(EnvironmentObserver observer) {
        observers.add(observer);
    }

    public void unregisterObserver(EnvironmentObserver observer) {
        observers.remove(observer);
    }

    public void updateSensorData(String sensorId, String parameter, double value) {
        if (sensorData.containsKey(sensorId)) {
            sensorData.get(sensorId).put(parameter, value);
            notifyObservers(sensorId, parameter, value);
        }
    }

    void notifyObservers(String sensorId, String parameter, double value) {
        String sensorType = sensors.get(sensorId).getName();
        String fieldId = String.valueOf(sensors.get(sensorId).getClass());
        String sensorInfo = sensorType + "(" + sensorId + ") in " + fieldId;

        for (EnvironmentObserver observer : observers) {
            observer.update(sensorInfo, value);
        }
    }
    class Sensor {
        private String name;

        public Sensor(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}
